package ysq.xyg.wxapi.api;


import com.github.pagehelper.StringUtil;
import ysq.xyg.base.util.SpringApplicationContextUtil;
import ysq.xyg.web.model.po.WebAccount;
import ysq.xyg.web.model.vo.WebAccountVo;
import ysq.xyg.web.service.WebAccountService;

import java.util.HashMap;
import java.util.Map;

/**
 * 缓存工具类；
 * 目前使用 服务器内存的方式；
 *
 */
public class WxMemoryCacheClient {
	private final static WebAccountService wxAccountService = (WebAccountService) SpringApplicationContextUtil.getBean("webAccountService");
	//服务器内存的方式缓存wxAccountInfo
	private static Map<String,WebAccount> wxAccountInfoMap = new HashMap<String,WebAccount>();

	//updateType：0,不更新到数据库，1、公众号token,2、jsToken，3、小程序token
	public static void addWxAccountInfo(WebAccount account,int updateType){
		wxAccountInfoMap.put(account.getId(), account);
		if(updateType==1){
			WebAccount wxAccount=acceptEntity();
			if(StringUtil.isNotEmpty(account.getAccessToken())){
				wxAccount.setAccessToken(account.getAccessToken());
				wxAccount.setExpiresIn(account.getExpiresIn());
				wxAccount.setAccessTokenEndTime(account.getAccessTokenEndTime());
			}
			wxAccountService.updateByPrimaryKey(wxAccount);
		}else if(updateType==2){
			WebAccount wxAccount=acceptEntity();
			if(StringUtil.isNotEmpty(account.getAccessToken())){
				wxAccount.setJsTicket(account.getJsTicket());
				wxAccount.setJsTicketEndTime(account.getJsTicketEndTime());
			}
			wxAccountService.updateByPrimaryKey(wxAccount);
		}else if(updateType==3){
			WebAccount wxAccount=acceptEntity();
			if(StringUtil.isNotEmpty(account.getAccessToken())){
				wxAccount.setXcxAccessToken(account.getXcxAccessToken());
				wxAccount.setXcxAccessTokenEndTime(account.getXcxAccessTokenEndTime());
			}
			wxAccountService.updateByPrimaryKey(wxAccount);
		}
	}


	public static WebAccount getWxAccountInfo(String account){
		return wxAccountInfoMap.get(account);
	}

	//获取唯一的公众号,如果需要多账号，请自行处理
	public static WebAccount getSingleWxAccountInfo(){
		WebAccount sigleAccount = null;
		for(String key : wxAccountInfoMap.keySet()){
			sigleAccount = wxAccountInfoMap.get(key);
			break;
		}
		if(sigleAccount==null){
			sigleAccount=acceptWxAccountInfoForDatabases();
			addWxAccountInfo(sigleAccount,0);
		}
		return sigleAccount;
	}
	//删除
	public static void deleteSingleWxAccountInfo(){
		wxAccountInfoMap.clear();
	}

	private static WebAccount acceptWxAccountInfoForDatabases(){
		WebAccount sigleAccount=new WebAccount();
		return  acceptEntity();
	}
	private static WebAccount acceptEntity(){
		return wxAccountService.acceptList(new WebAccountVo()).get(0);
	}
}